package cn.fzkj.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;

/**
 * 自定义客户端业务处理类
 */
@io.netty.channel.ChannelHandler.Sharable   // 允许多个客户端
public class ChannelHandler extends SimpleChannelInboundHandler<ByteBuf> {

    /**
     * 接收客户端发来的消息
     * @param ctx 上下文
     * @param byteBuf 消息
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
        String msg = byteBuf.toString(StandardCharsets.UTF_8);
        System.out.println(msg);

        // 发送消息给客户端
        ctx.writeAndFlush(Unpooled.copiedBuffer(msg + " nm " + msg, StandardCharsets.UTF_8));
    }
}

